package jq.core.text;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import org.mortbay.log.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WebPageUtil {
	private Logger log=LoggerFactory.getLogger(WebPageUtil.class);
	public String fetchPageContent(String urlStr) throws IOException {
		URL url = new URL(urlStr);
		BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
		String line = null;
		StringBuilder sb = new StringBuilder();
		while ((line = reader.readLine()) != null) {
			sb.append(line);
		}
		reader.close();
		return sb.toString();
	}

	public String fetchPageContent(String urlStr, String method, String data) throws IOException {
		URL url = new URL(urlStr);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setDoOutput(true);
		conn.setRequestMethod(method);
		conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

		OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
		writer.write(data);
		writer.flush();
		writer.close();

		if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
			if (log.isDebugEnabled()) log.debug("HTTP OK");
			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line = null;
			StringBuilder sb = new StringBuilder();
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\r\n");
			}
			reader.close();
			conn.disconnect();
			return sb.toString();
		} else {
			if (Log.isDebugEnabled()) Log.debug("HTTP ERROR");
			conn.disconnect();
			return null;
		}

	}

	public static void main(String args[]) throws IOException {
		System.err.println("showall=&to=" + URLEncoder.encode("Bahamanian Dollar (BSD)", "UTF-8") + "&amout=1&from="
				+ URLEncoder.encode("US Dollar (USD)", "UTF-8"));
		 String content =
		 new WebPageUtil().fetchPageContent("http://www.iccfx.com/convert.php",
		 "POST","showall=&to=Chinese+Yuan+Renminbi+%28CNY%29&amount=1&from=US+Dollar+%28USD%29");
		 System.err.println(content);

	}
}
